<template>
  <el-dialog
    v-model="visible"
    title="添加好友"
    width="500px"
    :before-close="handleClose"
  >
    <div class="add-friend-dialog">
      <!-- 搜索框 -->
      <div class="search-section">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入用户名、昵称或邮箱"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button 
              type="primary" 
              :loading="isSearching"
              @click="handleSearch"
            >
              搜索
            </el-button>
          </template>
        </el-input>
      </div>

      <!-- 搜索结果 -->
      <div class="search-results" v-if="searchResults.length > 0">
        <div class="result-header">
          <span>搜索结果 ({{ searchResults.length }})</span>
        </div>
        <div class="user-list">
          <div 
            v-for="user in searchResults" 
            :key="user.id"
            class="user-item"
          >
            <div class="user-info">
              <el-avatar 
                :size="40" 
                :src="user.avatar"
                :alt="user.nickname"
              >
                {{ user.nickname?.charAt(0) || user.username?.charAt(0) }}
              </el-avatar>
              <div class="user-details">
                <div class="user-name">{{ user.nickname || user.username }}</div>
                <div class="user-username">@{{ user.username }}</div>
              </div>
            </div>
            <div class="user-actions">
              <el-button
                v-if="!isAlreadyFriend(user.id)"
                type="primary"
                size="small"
                :loading="sendingRequests.has(user.id)"
                @click="handleSendRequest(user)"
              >
                添加好友
              </el-button>
              <el-tag v-else type="success" size="small">
                已是好友
              </el-tag>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-else-if="hasSearched && !isSearching" class="empty-state">
        <el-empty 
          description="未找到相关用户"
          :image-size="80"
        />
      </div>

      <!-- 搜索提示 -->
      <div v-else-if="!hasSearched" class="search-hint">
        <el-icon class="hint-icon"><Search /></el-icon>
        <p>输入关键词搜索用户</p>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { apiService } from '@/services/api'
import { friendService } from '@/services/friend'
import { useFriendsStore } from '@/stores/friends'
import type { UserInfo } from '@/types'

interface Props {
  modelValue: boolean
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'friend-request-sent', user: UserInfo): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const friendsStore = useFriendsStore()

// 响应式数据
const searchKeyword = ref('')
const searchResults = ref<UserInfo[]>([])
const isSearching = ref(false)
const hasSearched = ref(false)
const sendingRequests = ref(new Set<number>())

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 检查是否已经是好友
const isAlreadyFriend = (userId: number): boolean => {
  return friendsStore.friendsList.some(friend => friend.id === userId)
}

// 搜索用户
const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }

  try {
    isSearching.value = true
    hasSearched.value = true
    
    const users = await apiService.searchUsers(searchKeyword.value.trim())
    searchResults.value = users
    
    if (users.length === 0) {
      ElMessage.info('未找到相关用户')
    }
  } catch (error: any) {
    console.error('搜索用户失败:', error)
    ElMessage.error(error.message || '搜索失败，请重试')
    searchResults.value = []
  } finally {
    isSearching.value = false
  }
}

// 发送好友请求
const handleSendRequest = async (user: UserInfo) => {
  try {
    sendingRequests.value.add(user.id)
    
    // 检查是否可以发送好友请求
    const canSend = await friendService.canSendFriendRequest(user.id)
    if (!canSend) {
      ElMessage.warning('无法向该用户发送好友请求')
      return
    }
    
    // 发送好友请求
    await friendService.sendFriendRequest(user.id, `你好，我想添加你为好友`)
    
    ElMessage.success(`已向 ${user.nickname || user.username} 发送好友请求`)
    emit('friend-request-sent', user)
    
    // 从搜索结果中移除该用户，避免重复发送
    searchResults.value = searchResults.value.filter(u => u.id !== user.id)
    
  } catch (error: any) {
    console.error('发送好友请求失败:', error)
    ElMessage.error(error.message || '发送好友请求失败')
  } finally {
    sendingRequests.value.delete(user.id)
  }
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
  // 重置状态
  searchKeyword.value = ''
  searchResults.value = []
  hasSearched.value = false
  sendingRequests.value.clear()
}
</script>

<style scoped>
.add-friend-dialog {
  padding: 10px 0;
}

.search-section {
  margin-bottom: 20px;
}

.search-results {
  max-height: 400px;
  overflow-y: auto;
}

.result-header {
  padding: 10px 0;
  border-bottom: 1px solid var(--el-border-color-light);
  margin-bottom: 10px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.user-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.user-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  border: 1px solid var(--el-border-color-light);
  border-radius: 8px;
  transition: all 0.2s;
}

.user-item:hover {
  border-color: var(--el-color-primary);
  background-color: var(--el-fill-color-lighter);
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.user-name {
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.user-username {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.user-actions {
  flex-shrink: 0;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
}

.search-hint {
  padding: 60px 0;
  text-align: center;
  color: var(--el-text-color-secondary);
}

.hint-icon {
  font-size: 48px;
  margin-bottom: 16px;
  color: var(--el-text-color-placeholder);
}

.search-hint p {
  margin: 0;
  font-size: 14px;
}

.dialog-footer {
  text-align: right;
}
</style>